package com.innovations.common.core.page;

import com.alibaba.fastjson2.JSONObject;
import com.innovations.common.core.text.Convert;
import com.innovations.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 表格数据处理
 *
 * @author dp
 */
@Slf4j
public class TableSupport {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        try {
            if (ServletUtils.getParameter(PAGE_NUM) == null) {
                String reqBody = ServletUtils.getRequest().getReader().readLine();
                JSONObject json = JSONObject.parseObject(reqBody);
                pageDomain.setPageNum(1);
                pageDomain.setPageSize(10);
                if (json != null) {
                    if (json.containsKey("pageNum")) {
                        pageDomain.setPageNum(Convert.toInt(json.get("pageNum"), 1));
                    }
                    if (json.containsKey("pageSize")) {
                        pageDomain.setPageSize(Convert.toInt(json.get("pageSize"), 10));
                    }
                }
            } else {
                pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
                pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
            }
        } catch (Exception e) {
            log.error("自动分页失败", e);
        }

        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        return pageDomain;
    }

    public static PageDomain buildPageRequest() {
        return getPageDomain();
    }
}
